package com.mehdiuz.backend.role.service.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.mehdiuz.backend.commons.config.OSSConfig;
import com.mehdiuz.backend.commons.property.OSSProperty;
import com.mehdiuz.backend.commons.utils.ResultCodeEnum;
import com.mehdiuz.backend.role.service.OSSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class OSSServiceImpl implements OSSService {

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private OSSProperty ossProperty;

    @Override
    public Map<String, Object> getOssSign() {
        String dir = new DateTime().toString("yyyy/MM/dd");
        Map<String,Object> respMap;
        OSS ossClient = ossConfig.ossClient();
        long expireTime = 30;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

        String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = ossClient.calculatePostSignature(postPolicy);
        respMap = new LinkedHashMap<>();
        //这些参数名必须要这样写，与官方文档一一对应
        respMap.put("OSSAccessKeyId", ossProperty.getAccessKeyId());
        respMap.put("policy", encodedPolicy);
        respMap.put("Signature", postSignature);
        respMap.put("dir", dir);
        respMap.put("host", ossProperty.getHost());
        respMap.put("expire", String.valueOf(expireEndTime / 1000));
        respMap.put("success_action_status", ResultCodeEnum.SUCCESS.getCode());

        return respMap;
    }
}
